<?php
// +----------------------------------------------------------------------
// | UCToo [ Universal Convergence Technology ]
// +----------------------------------------------------------------------
// | Copyright (c) 2014-2021 https://www.uctoo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Patrick <contact@uctoo.com>
// +----------------------------------------------------------------------

namespace uctoo\job;

use think\Cache;
use think\queue\Job;
use uctoo\ThinkEasyWeChat\Facade;

class UploadCloudDb
{

    public function fire(Job $job, $data){
        if ($job->attempts() > 30) {
            $job->delete();
            return true;
        }

        $applet = $data['applet'];
        $wechatopenInfoConfig = Cache::get('wechatopen_config');
        $openPlatform = Facade::openPlatform($wechatopenInfoConfig['app_id'],$wechatopenInfoConfig);
        $app = $openPlatform->miniProgram($applet['appid'],$applet['refresh_token']);
        /**
         * @var \app\util\src\MiniPrograme\CloudEnv\Client $cloud_env
         */
        $cloud_env = $app->register(new \uctoo\ThinkEasyWeChat\MiniProgram\CloudEnv\ServiceProvider)->cloud_env;
        // 校验云环境初始化状态
        $res = $cloud_env->getEnvInfo($applet['env']);
        if('NORMAL' !== $res['info_list'][0]['status']){
            $job->release(60);
            return true;
        }

        $cloud_db = $app->register(new \uctoo\ThinkEasyWeChat\MiniProgram\CloudDb\ServiceProvider())->cloud_db;
        /**
         * @var \app\util\src\MiniPrograme\CloudDb\Client $cloud_db
         */
        $res = $cloud_db->collectionGet(100,0);
        if(0 != $res['errcode']){
            $job->release(60);
            return true;
        }
        $cloud_dbs = $data['cloud_dbs']['dbs'];
        $exist_dbs = [];
        foreach ($res['collections'] as $collection){
            $exist_dbs[] = $collection['name'];
        }
        $dbs = array_values(array_diff($cloud_dbs,$exist_dbs));
        if(!$dbs){
            $job->delete();
            return true;
        }

        foreach ($dbs as $v){
            $cloud_db->collectionAdd($v);
        }

        //校验上传  此处不做细致校验
        $res = $cloud_db->collectionGet();
        if($res['pager']['Total'] < count($cloud_dbs)) {
            $job->release(60);
            return true;
        }

        $job->delete();

    }

    public function failed($data){

    }
}